package leetcode.median;

import java.util.Arrays;

/*
 * @Author liyifan
 * @Description 下一个排列
 * @Date 19:38 2022/7/11
 * @Param 
 * @return 
 **/
public class $31_NextPermutation {
    public void nextPermutation1(int[] nums) {
        int len = nums.length;
        if (len <= 1) {
            return;
        }
        for (int i = len - 1;i > 0;i--) {
            if (nums[i] > nums[i - 1]) {
                Arrays.sort(nums, i, len);
                for (int j = i; j < len; j++) {
                    if (nums[j] > nums[i - 1]) {
                        swap(nums, j, i - 1);
                        return;
                    }
                }
            }
        }
        Arrays.sort(nums);
    }

    public void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    public void reverse(int[] nums, int start) {
        int left = start, right = nums.length - 1;
        while (left < right) {
            swap(nums, left, right);
            left++;
            right--;
        }
    }

    public void nextPermutation(int[] nums) {
        int len = nums.length;
        if (len <= 1) {
            return;
        }
        for (int i = len - 1;i > 0;i--) {
            if (nums[i] > nums[i - 1]) {
                // 找到逆序对
                int j = i - 1;
                for (int k = len - 1;k >= i;k--) {
                    if (nums[k] > nums[j]) {
                        swap(nums, k, j);
                        reverse(nums, j + 1);
                        return;
                    }
                }
            }
        }
        Arrays.sort(nums);
    }
}
